import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Button, Col, Form, message, Row, Spin } from 'antd';
import { Ref, useEffect, useMemo, useRef, useState } from 'react';
import pageStyles from '@/common/pageLayout.less';
import { arieaEchoRender, onCloseModalCommon } from '@/utils';
import { ContacterAPI } from '../common/type';
import { addContacterService, editContacterService, getContacterService } from '../services';
import moment from 'moment';
import { UpdataSteps } from './UpdataSteps';
import { UpdataTable } from './UpdataTable';
import { UpdateModalForm } from './UpdateModalForm';
export const UpdateModal: React.FC<ContacterAPI.IUpdateModal> = ({ curRes, onClose, checkRows, isShowModal, reloadManage }) => {
  /**  弹框的ref */
  const updateModalRef: Ref<IOneModalRef> = useRef(null);

  /**  表单 form */
  const [updateForm] = Form.useForm();

  /** 步骤条-数  */
  const [stepCurrent, setStepCurrent] = useState<number>(0);

  /**  保存table选中id */
  const [saveSupplierInfo, setSaveSupplierInfo] = useState<Record<string, any>>({
    supplierKey: '',
    supplierInfo: {},
  });

  /**
   * 获取详情回调
   * @param res 接口返回处理
   */
  const getContacterCallback = (res: any) => {
    if (res && res?.msgFlag) {
      updateForm?.setFieldsValue({
        ...res?.obj,
        contaNode: arieaEchoRender(checkRows),
        birthday: checkRows?.birthday ? moment(checkRows?.birthday) : null,
      });
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入详情接口 */
  const { getContacterLoading, getContacterRun, getContacterInfo } = getContacterService(getContacterCallback);

  useEffect(() => {
    if (isShowModal && checkRows && checkRows?.id && checkRows?.modalType == 'edit') {
      let payload: any = {
        id: checkRows?.id,
      };
      getContacterRun(payload);
      setStepCurrent(1);
    }
  }, [checkRows, isShowModal]);

  /**
   * 调用新增编辑成功后的回调
   * @param res 接口返回数据
   */
  const updateCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadManage();
      onCloseModalCommon(updateModalRef);
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入新增 */
  const { addContacterLoading, addContacterRun } = addContacterService(updateCallback);

  /**  引入编辑  */
  const { editContacterLoading, editContacterRun } = editContacterService(updateCallback);

  /**保存联系人信息 */
  const saveContacterForm = () => {
    updateForm?.validateFields()?.then((values: any) => {
      let updatePaylod: any = {
        ...values,
        provinceCode: values?.contaNode?.length > 0 ? values?.contaNode?.[0] : null,
        cityCode: values?.contaNode?.length > 0 ? values?.contaNode?.[1] : null,
        countyCode: values?.contaNode?.length > 0 ? values?.contaNode?.[2] : null,
        birthday: values?.birthday ? values?.birthday.format('YYYY-MM-DD 00:00:00') : null,
        supplierID: saveSupplierInfo?.supplierKey,
      };
      delete updatePaylod['contaNode'];
      if (checkRows && checkRows?.id) {
        let editPayload: any = {
          ...updatePaylod,
          id: getContacterInfo?.id,
          versionNum: getContacterInfo?.versionNum,
        };
        editContacterRun(editPayload);
      } else {
        addContacterRun(updatePaylod);
      }
    });
  };

  /** 弹框脚步按钮 */
  const modalFoolterBtn = useMemo(() => {
    return (
      <>
        <Button
          onClick={() => {
            onCloseModalCommon(updateModalRef);
          }}
        >
          取消
        </Button>
        {stepCurrent == 0 && checkRows?.modalType != 'edit' && (
          <Button
            type="primary"
            onClick={() => {
              if (saveSupplierInfo?.supplierKey) {
                setStepCurrent(1);
              } else {
                message.warning('请选择供应商！');
              }
            }}
          >
            下一步
          </Button>
        )}
        {stepCurrent == 1 && checkRows?.modalType != 'edit' && (
          <Button
            type="primary"
            onClick={() => {
              setStepCurrent(0);
            }}
          >
            上一步
          </Button>
        )}
        {stepCurrent == 1 && (
          <Button type="primary" onClick={saveContacterForm}>
            确定
          </Button>
        )}
      </>
    );
  }, [stepCurrent, saveSupplierInfo?.supplierKey]);

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={updateModalRef}
        title={checkRows && checkRows?.id ? '编辑联系人' : '添加联系人'}
        width={document.body.clientWidth * 0.6}
        onCancel={onClose}
        bodyStyle={{
          padding: '5px 0px',
        }}
        centered
        confirmLoading={addContacterLoading || editContacterLoading || getContacterLoading}
        footer={modalFoolterBtn}
      >
        <Spin spinning={addContacterLoading || editContacterLoading || getContacterLoading}>
          <Row>
            {checkRows?.modalType != 'edit' && (
              <Col span={24}>
                <UpdataSteps stepCurrent={stepCurrent} />
              </Col>
            )}
            <Col span={24}>
              {stepCurrent == 0 && checkRows?.modalType != 'edit' && (
                <UpdataTable
                  defaultSupplierKey={saveSupplierInfo?.supplierKey}
                  curRes={curRes}
                  onSaveSelectRow={setSaveSupplierInfo}
                  getContacterInfo={getContacterInfo}
                />
              )}
              {stepCurrent == 1 && (
                <div className={pageStyles['fromView-styles']}>
                  <Form form={updateForm}>
                    <UpdateModalForm getContacterInfo={getContacterInfo} selectSupplierInfo={saveSupplierInfo?.supplierInfo} />
                  </Form>
                </div>
              )}
            </Col>
          </Row>
        </Spin>
      </OneModal>
    </>
  );
};
